import React, { useState } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Typography,
  Card
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined, 
  PlayCircleOutlined, 
  StopOutlined,
  BugOutlined
} from '@ant-design/icons';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import { motion } from 'framer-motion';
import { notification } from '../../../components/common'; // 导入自定义通知组件

const { Title, Text } = Typography;
const { Option } = Select;

interface CrawlerJob {
  id: number;
  name: string;
  url: string;
  status: 'running' | 'stopped' | 'pending' | 'error';
  frequency: string;
  lastRun: string;
  nextRun: string;
  createdBy: string;
  createdAt: string;
}

const CrawlersManagement: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [jobs, setJobs] = useState<CrawlerJob[]>([
    {
      id: 1,
      name: '新闻爬虫',
      url: 'https://news.example.com',
      status: 'running',
      frequency: '每小时',
      lastRun: '2023-10-20 14:30',
      nextRun: '2023-10-20 15:30',
      createdBy: 'admin',
      createdAt: '2023-01-15'
    },
    {
      id: 2,
      name: '电商爬虫',
      url: 'https://shop.example.com',
      status: 'stopped',
      frequency: '每天',
      lastRun: '2023-10-19 09:15',
      nextRun: '-',
      createdBy: 'user1',
      createdAt: '2023-03-22'
    },
    {
      id: 3,
      name: '社交爬虫',
      url: 'https://social.example.com',
      status: 'error',
      frequency: '每2小时',
      lastRun: '2023-10-10 16:45',
      nextRun: '2023-10-10 18:45',
      createdBy: 'user2',
      createdAt: '2023-05-10'
    }
  ]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingJob, setEditingJob] = useState<CrawlerJob | null>(null);
  const [form] = Form.useForm();

  // 频率选项
  const frequencyOptions = [
    '每分钟',
    '每5分钟',
    '每15分钟',
    '每30分钟',
    '每小时',
    '每2小时',
    '每6小时',
    '每天',
    '每周',
    '每月'
  ];

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '爬虫名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '目标URL',
      dataIndex: 'url',
      key: 'url',
      render: (url: string) => (
        <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: theme.glowColor }}>
          {url}
        </a>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: 'running' | 'stopped' | 'pending' | 'error') => {
        const statusConfig = {
          running: { color: 'green', text: '运行中' },
          stopped: { color: 'red', text: '已停止' },
          pending: { color: 'orange', text: '待运行' },
          error: { color: 'volcano', text: '错误' }
        };
        
        const config = statusConfig[status];
        return (
          <motion.div
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
            animate={{ 
              scale: status === 'running' ? [1, 1.05, 1] : 1,
              transition: status === 'running' ? { 
                duration: 1,
                repeat: Infinity,
                repeatType: "reverse"
              } : {}
            }}
          >
            <Tag color={config.color}>{config.text}</Tag>
          </motion.div>
        );
      }
    },
    {
      title: '频率',
      dataIndex: 'frequency',
      key: 'frequency'
    },
    {
      title: '上次运行',
      dataIndex: 'lastRun',
      key: 'lastRun'
    },
    {
      title: '下次运行',
      dataIndex: 'nextRun',
      key: 'nextRun'
    },
    {
      title: '创建者',
      dataIndex: 'createdBy',
      key: 'createdBy'
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: CrawlerJob) => (
        <Space size="middle">
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              type="primary" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => handleViewJob(record)}
              style={{ 
                background: theme.glowColor,
                borderColor: theme.glowColor
              }}
            >
              查看
            </Button>
          </motion.div>
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => handleEditJob(record)}
            >
              编辑
            </Button>
          </motion.div>
          {record.status === 'running' ? (
            <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
              <Button 
                icon={<StopOutlined />} 
                size="small"
                onClick={() => handleStopJob(record)}
                style={{ 
                  background: '#ff4d4f',
                  borderColor: '#ff4d4f',
                  color: 'white'
                }}
              >
                停止
              </Button>
            </motion.div>
          ) : (
            <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
              <Button 
                icon={<PlayCircleOutlined />} 
                size="small"
                type="primary"
                onClick={() => handleStartJob(record)}
                style={{ 
                  background: theme.glowColor,
                  borderColor: theme.glowColor
                }}
              >
                启动
              </Button>
            </motion.div>
          )}
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              icon={<DeleteOutlined />} 
              size="small"
              danger
              onClick={() => handleDeleteJob(record)}
            >
              删除
            </Button>
          </motion.div>
        </Space>
      )
    }
  ];

  const handleViewJob = (job: CrawlerJob) => {
    Modal.info({
      title: '爬虫任务详情',
      content: (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Card style={{ 
            background: theme.cardBackground,
            borderColor: theme.cardBorder
          }}>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
            >
              <p><Text strong>爬虫名称:</Text> {job.name}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.2 }}
            >
              <p><Text strong>目标URL:</Text> <a href={job.url} target="_blank" rel="noopener noreferrer">{job.url}</a></p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <p><Text strong>状态:</Text> {job.status}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.4 }}
            >
              <p><Text strong>频率:</Text> {job.frequency}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.5 }}
            >
              <p><Text strong>上次运行:</Text> {job.lastRun}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.6 }}
            >
              <p><Text strong>下次运行:</Text> {job.nextRun}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.7 }}
            >
              <p><Text strong>创建者:</Text> {job.createdBy}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.8 }}
            >
              <p><Text strong>创建时间:</Text> {job.createdAt}</p>
            </motion.div>
          </Card>
        </motion.div>
      ),
      okText: '确定',
      icon: <BugOutlined style={{ color: theme.glowColor }} />
    });
  };

  const handleEditJob = (job: CrawlerJob) => {
    setEditingJob(job);
    form.setFieldsValue(job);
    setIsModalVisible(true);
  };

  const handleStartJob = (job: CrawlerJob) => {
    setJobs(jobs.map(j => 
      j.id === job.id ? { ...j, status: 'running', lastRun: new Date().toLocaleString(), nextRun: '2023-10-20 16:30' } : j
    ));
    // 使用自定义通知组件替换 message.success
    notification.success({
      title: '爬虫任务启动',
      message: '爬虫任务已成功启动'
    });
  };

  const handleStopJob = (job: CrawlerJob) => {
    setJobs(jobs.map(j => 
      j.id === job.id ? { ...j, status: 'stopped', nextRun: '-' } : j
    ));
    // 使用自定义通知组件替换 message.success
    notification.success({
      title: '爬虫任务停止',
      message: '爬虫任务已成功停止'
    });
  };

  const handleDeleteJob = (job: CrawlerJob) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除爬虫任务 "${job.name}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        setJobs(jobs.filter(j => j.id !== job.id));
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '爬虫任务删除',
          message: '爬虫任务已成功删除'
        });
      },
      icon: <DeleteOutlined style={{ color: '#ff4d4f' }} />
    });
  };

  const handleAddJob = () => {
    setEditingJob(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (editingJob) {
        // 更新爬虫任务
        setJobs(jobs.map(job => 
          job.id === editingJob.id ? { ...job, ...values } : job
        ));
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '爬虫任务更新',
          message: '爬虫任务已成功更新'
        });
      } else {
        // 添加爬虫任务
        const newJob = {
          ...values,
          id: jobs.length + 1,
          status: 'stopped',
          lastRun: '-',
          nextRun: '-',
          createdBy: 'admin',
          createdAt: new Date().toISOString().split('T')[0]
        };
        setJobs([...jobs, newJob]);
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '爬虫任务添加',
          message: '爬虫任务已成功添加'
        });
      }
      setIsModalVisible(false);
    });
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
    >
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: 24 
      }}>
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Title level={3} style={{ color: theme.textPrimary, margin: 0 }}>
            爬虫管理
          </Title>
        </motion.div>
        <motion.div
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.3 }}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAddJob}
            style={{ 
              background: theme.glowColor,
              borderColor: theme.glowColor,
              boxShadow: theme.cardShadow
            }}
          >
            添加爬虫任务
          </Button>
        </motion.div>
      </div>
      
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1 }}
      >
        <Table
          dataSource={jobs}
          columns={columns}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true
          }}
          style={{
            background: theme.cardBackground,
            borderRadius: '12px',
            overflow: 'hidden',
            boxShadow: theme.cardShadow
          }}
          scroll={{ x: true }}
        />
      </motion.div>
      
      <Modal
        title={editingJob ? "编辑爬虫任务" : "添加爬虫任务"}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        okText="确定"
        cancelText="取消"
        width={600}
        style={{ 
          borderRadius: '12px'
        }}
      >
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Form form={form} layout="vertical">
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
            >
              <Form.Item
                name="name"
                label="爬虫名称"
                rules={[{ required: true, message: '请输入爬虫名称' }]}
              >
                <Input 
                  placeholder="请输入爬虫名称"
                  style={{ 
                    borderRadius: '8px'
                  }}
                />
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.2 }}
            >
              <Form.Item
                name="url"
                label="目标URL"
                rules={[
                  { required: true, message: '请输入目标URL' },
                  { type: 'url', message: '请输入有效的URL' }
                ]}
              >
                <Input 
                  placeholder="请输入目标URL"
                  style={{ 
                    borderRadius: '8px'
                  }}
                />
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <Form.Item
                name="frequency"
                label="运行频率"
                rules={[{ required: true, message: '请选择运行频率' }]}
              >
                <Select style={{ borderRadius: '8px' }}>
                  {frequencyOptions.map((option, index) => (
                    <motion.div
                      key={option}
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ duration: 0.3, delay: 0.4 + index * 0.05 }}
                    >
                      <Option key={option} value={option}>{option}</Option>
                    </motion.div>
                  ))}
                </Select>
              </Form.Item>
            </motion.div>
          </Form>
        </motion.div>
      </Modal>
    </motion.div>
  );
};

export default CrawlersManagement;